package com.neusoft.healthcity.config.scheduled;

import com.neusoft.healthcity.config.RandomNum;
import com.neusoft.healthcity.entity.ViewDeathInfo;
import com.neusoft.healthcity.service.ViewDeathInfoService;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class XmlGeneratorDeath {

    @Autowired
    private ViewDeathInfoService deathInfoService;

    private Logger logger = LoggerFactory.getLogger(XmlGeneratorDeath.class);
    //区域编码
    @Value("${xmlCreate.reportZoneCode}")
    private String reportZoneCode;
    //机构编码
    @Value("${xmlCreate.reportOrgCode}")
    private String reportOrgCode;
    //授权码
    @Value("${xmlCreate.license}")
    private String license;
    //生成xml文件存放位置
    @Value("${xmlCreate.death.xmlFileLocation}")
    private String XMLfilelocation;


    String startDate = null;
    String endDate = null;

    @Scheduled(cron = "0 15 0 * * ?")
    public void xmlGeneratorDeathScheduled() {
        logger.info("-----------death data begin -----------");
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        startDate = format.format(date);
        //startDate = "20180328101538";

        logger.info("--------" + startDate + "--------");

        List<ViewDeathInfo> scheduledInfectious = deathInfoService.getScheduledDeathInfo(startDate, endDate);

        //第一次的结束时间为下一次的开始时间x`
        endDate = startDate;

        logger.info("--------" + endDate + "--------");
        //根节点
        Element root = new Element("EDRDocument");

        //将根节点添加到文档中
        Document document = new Document(root);

        //文档标识ID
        String documentId=reportOrgCode+"-"
                +new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"-"
                + RandomNum.get5NumString();
        //子节点header
        Element elementHeader = new Element("Header");
        elementHeader.addContent(new Element("DocumentId").setText(documentId));
        elementHeader.addContent(new Element("OperateType").setText("Add"));
        elementHeader.addContent(new Element("BusinessActivityIdentification").setText("DeathReg"));
        elementHeader.addContent(new Element("ReportZoneCode").setText(reportZoneCode));
        elementHeader.addContent(new Element("ReportOrgCode").setText(reportOrgCode));
        elementHeader.addContent(new Element("License").setText(license));
        root.addContent(elementHeader);

        //子节点body
        Element elementBody = new Element("Body");
        root.addContent(elementBody);

        for (int i = 0; i < scheduledInfectious.size(); i++) {
            //body子节点下的子节点
            Element elementBodyPersonInfo = new Element("PersonInfo");
            //将加子节点到父节点
            elementBody.addContent(elementBodyPersonInfo);
            //定义传染病视图对象
            ViewDeathInfo deathInfo = scheduledInfectious.get(i);

            // 添加子节点并赋值
            //患者姓名
            elementBodyPersonInfo.addContent(new Element("PatientName").setText(deathInfo.getPatientname()));
            //身份证件类别代码
            elementBodyPersonInfo.addContent(new Element("IdCardTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getIdcardtypecode()).setText(deathInfo.getIdcardtype()));
            //身份证件号
            elementBodyPersonInfo.addContent(new Element("IdCard").setText(deathInfo.getIdcard()));
            //性别代码
            elementBodyPersonInfo.addContent(new Element("GenderCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getGendercode()).setText(deathInfo.getGender()));
            //出生日期
            elementBodyPersonInfo.addContent(new Element("BirthDate").setText(deathInfo.getBirthdate()));
            //国籍代码
            elementBodyPersonInfo.addContent(new Element("NationalityCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getNationalitycode()).setText(deathInfo.getNationality()));
            //民族代码
            elementBodyPersonInfo.addContent(new Element("NationCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getNationcode()).setText(deathInfo.getNationcode()));
            //学历代码
            elementBodyPersonInfo.addContent(new Element("EducationLevelCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getEducationlevelcode()).setText(deathInfo.getEducationlevel()));
            //户籍类别代码
            elementBodyPersonInfo.addContent(new Element("DomicileAddressAttributionCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getDomicileaddressattributioncode()).setText(deathInfo.getDomicileaddressattribution()));
            //户籍地址编码
            elementBodyPersonInfo.addContent(new Element("DomicileAddressCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getDomicileaddresscode()).setText(deathInfo.getDomicileaddress()));
            //户籍所在地址村编码
            elementBodyPersonInfo.addContent(new Element("PermanentVillage").setText(deathInfo.getPermanentVillage()));
            //户籍详细地址
            elementBodyPersonInfo.addContent(new Element("DomicileAdrressDetails").setText(deathInfo.getDomicileadrressdetails()));
            // 现住址类别/生前住址类别
            elementBodyPersonInfo.addContent(new Element("LivingAddressAttributionCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getLivingaddressattributioncode()).setText(deathInfo.getLivingaddressattribution()));
            //现住地区编码/生前地区编码
            elementBodyPersonInfo.addContent(new Element("LivingAddressCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getLivingaddresscode()).setText(deathInfo.getLivingaddress()));
            //死者生前常住地址村编码
            elementBodyPersonInfo.addContent(new Element("CurrentVillage").setText(deathInfo.getCurrentvillage()));
            //现住详细地址/生前详细住址
            elementBodyPersonInfo.addContent(new Element("LivingAddressDetails").setText(deathInfo.getLivingaddressdetails()));
            //工作单位/学校名称
            elementBodyPersonInfo.addContent(new Element("EmployerOrgName").setText(deathInfo.getEmployerorgname()));
            //人群分类代码
            elementBodyPersonInfo.addContent(new Element("NultitudeTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getNultitudetypecode()).setText(deathInfo.getNultitudetype()));
            //个人身份代码
            elementBodyPersonInfo.addContent(new Element("PersonTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getPersontypecode()).setText(deathInfo.getPersontype()));
            //人群分类代码
            elementBodyPersonInfo.addContent(new Element("OtherNultitudeType").setText(deathInfo.getOthernultitudetype()));
            //婚姻状况代码
            elementBodyPersonInfo.addContent(new Element("MaritalStatusCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getMaritalstatuscode()).setText(deathInfo.getMaritalstatus()));
            //联系人/监护人姓名
            elementBodyPersonInfo.addContent(new Element("Contacts").setText(deathInfo.getContacts()));
            //联系人/监护人电话号码
            elementBodyPersonInfo.addContent(new Element("ContactsTel").setText(deathInfo.getContactstel()));
            //联系人/监护人与本人关系代码
            elementBodyPersonInfo.addContent(new Element("ContactsRelCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getContactsrelcode()).setText(deathInfo.getContactsrel()));


            //添加body节点下的DiseaseInfo节点   病例报告信息
            Element elementBodyDeathInfo = new Element("DeathInfo");
            //将DiseaseInfo节点添加到body节点
            elementBody.addContent(elementBodyDeathInfo);


            //添加子节点
            //数据ID
            elementBodyDeathInfo.addContent(new Element("Id").setText(deathInfo.getId()));
            //死亡卡编号
            elementBodyDeathInfo.addContent(new Element("DeathCardCode").setText(deathInfo.getDeathcardcode()));
            //死亡日期
            elementBodyDeathInfo.addContent(new Element("DeathDate").setText(deathInfo.getDeathdate()));
            //死亡地点类别
            elementBodyDeathInfo.addContent(new Element("DeathPlaceCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getDeathplacecode()).setText(deathInfo.getDeathplace()));
            //死亡时是否处于妊娠期或妊娠终止后42天内
            elementBodyDeathInfo.addContent(new Element("WomanTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getWomantypecode()).setText(deathInfo.getWomantype()));
            //家属联系地址或工作单位
            elementBodyDeathInfo.addContent(new Element("ContactsAddr").setText(deathInfo.getContactsaddr()));
            //（a）直接死亡原因名称
            elementBodyDeathInfo.addContent(new Element("CauseA").setText(deathInfo.getContactsaddr()));
            elementBodyDeathInfo.addContent(new Element("CauseIcdA").setText(deathInfo.getCauseicda()));
            elementBodyDeathInfo.addContent(new Element("IntervalTimeA").setText(deathInfo.getIntervaltimea()));
            elementBodyDeathInfo.addContent(new Element("IntervalTimeUnitACode").setText(deathInfo.getIntervaltimeunitacode()));
            elementBodyDeathInfo.addContent(new Element("CauseB").setText(deathInfo.getCauseb()));
            elementBodyDeathInfo.addContent(new Element("CauseIcdB").setText(deathInfo.getCauseicdb()));
            elementBodyDeathInfo.addContent(new Element("IntervalTimeB").setText(deathInfo.getIntervaltimeb()));
            elementBodyDeathInfo.addContent(new Element("IntervalTimeUnitBCode").setText(deathInfo.getIntervaltimeunitbcode()));
            elementBodyDeathInfo.addContent(new Element("CauseC").setText(deathInfo.getCausec()));
            elementBodyDeathInfo.addContent(new Element("CauseIcdC").setText(deathInfo.getCauseicdc()));
            elementBodyDeathInfo.addContent(new Element("IntervalTimeC").setText(deathInfo.getIntervaltimec()));
            elementBodyDeathInfo.addContent(new Element("IntervalTimeUnitCCode").setText(deathInfo.getIntervaltimeunitccode()));
            elementBodyDeathInfo.addContent(new Element("CauseD").setText(deathInfo.getCaused()));
            elementBodyDeathInfo.addContent(new Element("CauseIcdD").setText(deathInfo.getCauseicdd()));
            elementBodyDeathInfo.addContent(new Element("IntervalTimeD").setText(deathInfo.getIntervaltimed()));
            elementBodyDeathInfo.addContent(new Element("IntervalTimeUnitDCode").setText(deathInfo.getIntervaltimeunitdcode()));
            elementBodyDeathInfo.addContent(new Element("CauseOther").setText(deathInfo.getCauseother()));
            elementBodyDeathInfo.addContent(new Element("CauseIcdOther").setText(deathInfo.getCauseicdother()));
            elementBodyDeathInfo.addContent(new Element("CauseIcdBasic").setText(deathInfo.getCauseicdbasic()));
            //最高诊断单位
            elementBodyDeathInfo.addContent(new Element("DiagnoseOrgCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getDiagnoseorgcode()).setText(deathInfo.getDiagnoseorg()));
            //最高诊断依据
            elementBodyDeathInfo.addContent(new Element("DiagnoseEvidenceCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getDiagnoseevidencecode()).setText(deathInfo.getDiagnoseevidence()));
            //住院号
            elementBodyDeathInfo.addContent(new Element("HospitalNumber").setText(deathInfo.getHospitalnumber()));
            elementBodyDeathInfo.addContent(new Element("Doctor").setText(deathInfo.getDoctor()));
            elementBodyDeathInfo.addContent(new Element("FillCardDate").setText(deathInfo.getFillcarddate()));
            elementBodyDeathInfo.addContent(new Element("ReportUser").setText(deathInfo.getReportuser()));
            elementBodyDeathInfo.addContent(new Element("Police").setText(deathInfo.getPolice()));
            elementBodyDeathInfo.addContent(new Element("Remarks").setText(deathInfo.getRemarks()));
            elementBodyDeathInfo.addContent(new Element("SymptomsCode").setText(deathInfo.getSymptomscode()));
            elementBodyDeathInfo.addContent(new Element("Respondents").setText(deathInfo.getRespondents()));
            elementBodyDeathInfo.addContent(new Element("RespondentsRelCode").setText(deathInfo.getRespondentsrelcode()));
            elementBodyDeathInfo.addContent(new Element("RespondentsAddr").setText(deathInfo.getRespondentsaddr()));
            elementBodyDeathInfo.addContent(new Element("RespondentsTelPhone").setText(deathInfo.getRespondentstelphone()));
            elementBodyDeathInfo.addContent(new Element("CauseInfer").setText(deathInfo.getCauseinfer()));
            elementBodyDeathInfo.addContent(new Element("Investigator").setText(deathInfo.getInvestigator()));
            elementBodyDeathInfo.addContent(new Element("InvestigationDate").setText(deathInfo.getInvestigationdate()));
            elementBodyDeathInfo.addContent(new Element("CheckUser").setText(deathInfo.getCheckuser()));
            elementBodyDeathInfo.addContent(new Element("FirstCheckDate").setText(deathInfo.getFirstcheckdate()));
            elementBodyDeathInfo.addContent(new Element("CheckDate").setText(deathInfo.getCheckdate()));

            Element elementOperateInfo = new Element("OperateInfo");
            elementOperateInfo.addContent(new Element("OperateTypeCode").setText(deathInfo.getOperatetypecode()));
            elementOperateInfo.addContent(new Element("OperateZoneCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getOperatezonecode()).setText(deathInfo.getOperatezone()));
            elementOperateInfo.addContent(new Element("OperateOrgCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getOperateorgcode()).setText(deathInfo.getOperateorg()));
            elementOperateInfo.addContent(new Element("OperateUser").setText(deathInfo.getOperateuser()));
            elementOperateInfo.addContent(new Element("OperateUserTypeCode")
                    .setAttribute("version", "1.0").setAttribute("value", deathInfo.getOperateusertypecode()).setText(deathInfo.getOperateusertype()));
            elementOperateInfo.addContent(new Element("OperateDate").setText(deathInfo.getOperatedate()));
            elementBodyDeathInfo.addContent(elementOperateInfo);

            // 输出 books.xml 文件；
            // 使xml文件 缩进效果
            Format prettyFormat = Format.getPrettyFormat();
            XMLOutputter XMLOut = new XMLOutputter(prettyFormat);
            try {
                XMLOut.output(document, new FileOutputStream(XMLfilelocation + startDate + ".xml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.info("----------- end   -----------");
        }
    }

}
